package com.wcgksoft.controller.system;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wcgksoft.common.util.FileHandleUtil;
import com.wcgksoft.common.util.Layui;
import com.wcgksoft.entity.Alert.Alarm;
import com.wcgksoft.entity.ZData.BasicData;
import com.wcgksoft.entity.dataAnalysis.DepartProjectData;
import com.wcgksoft.entity.notic.Notic;
import com.wcgksoft.entity.system.EnterpriseProject;
import com.wcgksoft.entity.system.OnTrial;
import com.wcgksoft.entity.system.SysUser;
import com.wcgksoft.service.BasicDataService;
import com.wcgksoft.service.DataAnalysis.DepartProjectDataService;
import com.wcgksoft.service.DataAnalysis.ThresholdService;
import com.wcgksoft.service.EnterpriseProjectService;
import com.wcgksoft.service.alarm.AlarmService;
import com.wcgksoft.service.notic.NoticService;
import com.wcgksoft.service.openAccount.OpenAccountService;
import com.wcgksoft.service.system.OnTrialService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("home")
public class homeController {


  @Autowired
  private AlarmService alarmService;

  @Autowired
  private NoticService noticService;
  @Autowired
  private OpenAccountService openAccountService;
  @Autowired
  private OnTrialService onTrialService;
  @Autowired
  private BasicDataService basicDataService;
  @Autowired
  private DepartProjectDataService departProjectDataService;
  @Autowired
  private ThresholdService thresholdService;
  @Autowired
  private EnterpriseProjectService enterpriseProjectService;


  @RequestMapping(value = "console")
  public String console(HttpServletRequest req, ModelMap modelMap) {

    SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
    DetachedCriteria notic = DetachedCriteria.forClass(Notic.class);
    notic.add(Restrictions.eq("sysuserid", sysUser.getId()));
    notic.addOrder(Order.desc("time"));
    List<Notic> byConditions = noticService.findByConditions(notic);
    if (byConditions.size() > 0) {
      Notic notic1 = byConditions.get(0);
      System.out.println("标题" + notic1.getTitle());
      modelMap.put("notics", notic1);
    }
    DetachedCriteria sysuser = DetachedCriteria.forClass(SysUser.class);
    sysuser.add(Restrictions.eq("enterprise.id", sysUser.getEnterprise().getId()));
    List<SysUser> userList = openAccountService.findByConditions(sysuser);
    modelMap.put("toluser", userList.size());

    DetachedCriteria manageuser = DetachedCriteria.forClass(SysUser.class);
    manageuser.add(Restrictions.eq("enterprise.id", sysUser.getEnterprise().getId()));
    manageuser.createAlias("sysRole", "role");
    manageuser.createAlias("sysRole.sysRoleCode", "rolecode");
    manageuser.add(Restrictions.eq("rolecode.role_number", "manage"));
    List<SysUser> manageuseruserList = openAccountService.findByConditions(manageuser);
    modelMap.put("manageuser", manageuseruserList.size());

    DetachedCriteria sysusercon = DetachedCriteria.forClass(SysUser.class);
    sysusercon.add(Restrictions.eq("enterprise.id", sysUser.getEnterprise().getId()));
    sysusercon.createAlias("sysRole", "role");
    sysusercon.createAlias("role.sysRoleCode", "rolecode");
    sysusercon.add(Restrictions.eq("rolecode.role_number", "construction"));
    List<SysUser> conditionsList = openAccountService.findByConditions(sysusercon);
    modelMap.put("constructionuser", conditionsList.size());
    /*下面是查询 豆腐块*/
    DetachedCriteria detachedCriteriaep = DetachedCriteria.forClass(EnterpriseProject.class);
    detachedCriteriaep.add(Restrictions.eq("enterprise.id",sysUser.getEnterprise().getId()));
    detachedCriteriaep.add(Restrictions.eq("parentId",-1));
    List<EnterpriseProject> enterpriseProjects = enterpriseProjectService.findByConditions(detachedCriteriaep);
    JSONObject jsonObject = new JSONObject();
    for (EnterpriseProject project : enterpriseProjects) {
      JSONArray objectarr = new JSONArray();
      DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DepartProjectData.class);
      detachedCriteria.add(Restrictions.eq("bbbbid", project.getId()));
      //detachedCriteria.add(Restrictions.eq("",""));
      List<DepartProjectData> projectData = departProjectDataService.findByConditions(detachedCriteria);

      for (DepartProjectData data : projectData) {
        DetachedCriteria alarms = DetachedCriteria.forClass(Alarm.class);
        alarms.createAlias("departProjectData", "departProjectData");
        alarms.add(Restrictions.eq("departProjectData.id", data.getId()));
        alarms.add(Restrictions.eq("stitas",1));
        List<Alarm> all1 = alarmService.findByConditions(alarms);

        if (all1.size()>0){
          data.setCode(1);
        }

        DetachedCriteria criteria = DetachedCriteria.forClass(BasicData.class);
        criteria.add(Restrictions.eq("com", data.getCom()));
        criteria.add(Restrictions.eq("no", data.getEquipment().getE_number()));
        criteria.add(Restrictions.eq("datatype", data.getDataType().getD_key()));
        criteria.addOrder(Order.desc("Acquisitiontime"));
        //List<Date> listdate = new ArrayList<>();
        //List<String> listdata = new ArrayList<>();
        List<BasicData> datas = basicDataService.findByConditions(criteria);
        if (datas.size()>0){
          //datas.get(0);
          HashMap<Object, Object> map = new HashMap<>();
          map.put("data",datas.get(0));
          map.put("porjectdata",data);
          objectarr.add(map);
        }
      }
      if (objectarr.size()>0){
        jsonObject.put(project.getProjectName(),objectarr);
      }


    }

    modelMap.put("datablock",jsonObject);
    return "home/consoleok";//返回 /WEB-INF/view 下的 login.html
  }

  @RequestMapping(value = "homepage1")
  public String homepage1(HttpServletRequest req, ModelMap modelMap) {

    SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
    DetachedCriteria notic = DetachedCriteria.forClass(Notic.class);
    notic.add(Restrictions.eq("sysuserid", sysUser.getId()));
    notic.addOrder(Order.desc("time"));
    List<Notic> byConditions = noticService.findByConditions(notic);
    if (byConditions.size() > 0) {
      Notic notic1 = byConditions.get(0);
      System.out.println("标题" + notic1.getTitle());
      modelMap.put("notics", notic1);
    }
    DetachedCriteria sysusercon = DetachedCriteria.forClass(SysUser.class);
    Session session = SecurityUtils.getSubject().getSession();
    EnterpriseProject enterpriseProject = (EnterpriseProject) session.getAttribute("area");
    Integer id2 = enterpriseProject.getId();
    sysusercon.add(Restrictions.eq("enterprise.id", sysUser.getEnterprise().getId()));
    sysusercon.createAlias("sysRole", "role");
    sysusercon.createAlias("role.sysRoleCode", "rolecode");
    sysusercon.add(Restrictions.eq("rolecode.role_number", "construction"));
    sysusercon.add(Restrictions.eq("areaid", id2));
    List<SysUser> conditionsList = openAccountService.findByConditions(sysusercon);
    modelMap.put("constructionuser", conditionsList.size());
    return "home/homepage1";//返回 /WEB-INF/view 下的 login.html
  }

  @RequestMapping(value = "homepage2")
  public String homepage2(HttpServletRequest req, ModelMap modelMap) {

    SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
    DetachedCriteria notic = DetachedCriteria.forClass(Notic.class);
    notic.add(Restrictions.eq("sysuserid", sysUser.getId()));
    notic.addOrder(Order.desc("time"));
    List<Notic> byConditions = noticService.findByConditions(notic);
    if (byConditions.size() > 0) {
      Notic notic1 = byConditions.get(0);
      System.out.println("标题" + notic1.getTitle());
      modelMap.put("notics", notic1);
    }

    return "home/homepage2";//返回 /WEB-INF/view 下的 login.html
  }


  @RequestMapping(value = "technologymain")
  public String technologymain(HttpServletRequest req, ModelMap modelMap) {

    SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
    DetachedCriteria notic = DetachedCriteria.forClass(Notic.class);
    notic.add(Restrictions.eq("sysuserid", sysUser.getId()));
    notic.addOrder(Order.desc("time"));
    List<Notic> byConditions = noticService.findByConditions(notic);
    if (byConditions.size() > 0) {
      Notic notic1 = byConditions.get(0);
      System.out.println("标题" + notic1.getTitle());
      modelMap.put("notics", notic1);
    }
    List<SysUser> all = openAccountService.findAll(SysUser.class);
    modelMap.put("toluser", all.size());
    List<OnTrial> all1 = onTrialService.findAll(OnTrial.class);
    modelMap.put("toltrial", all1.size());
    return "home/technologymain";//返回 /WEB-INF/view 下的 login.html
  }

  @RequestMapping(value = "governmentmain")
  public String governmentmain(HttpServletRequest req, ModelMap modelMap) {

    SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
    DetachedCriteria notic = DetachedCriteria.forClass(Notic.class);
    notic.add(Restrictions.eq("sysuserid", sysUser.getId()));
    notic.addOrder(Order.desc("time"));
    List<Notic> byConditions = noticService.findByConditions(notic);
    if (byConditions.size() > 0) {
      Notic notic1 = byConditions.get(0);
      System.out.println("标题" + notic1.getTitle());
      modelMap.put("notics", notic1);
    }

    return "home/governmentmain";//返回 /WEB-INF/view 下的 login.html
  }

  /**
   * @throws
   * @title TODO
   * @description 首页豆腐块查询
   * @author 阿良
   * @param: request
   * @param: data
   * @param: meun
   * @updateTime 2020/3/11 10:31
   * @return: com.wcgksoft.common.util.Layui
   */
  @ResponseBody
  @RequestMapping(value = "findHomeblock")
  public JSONArray update(HttpServletRequest request) throws Exception {
    Session session = SecurityUtils.getSubject().getSession();//得到工具类
    EnterpriseProject enterpriseProject = (EnterpriseProject) session.getAttribute("project");//获取选中的片区/区域
    Integer id2 = enterpriseProject.getId();
    SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");//获得企业用户
    //sysusercon.add(Restrictions.eq("enterprise.id", sysUser.getEnterprise().getId()));
    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DepartProjectData.class);
    detachedCriteria.add(Restrictions.eq("bbbbid", id2));
    //detachedCriteria.add(Restrictions.eq("",""));
    List<DepartProjectData> projectData = departProjectDataService.findByConditions(detachedCriteria);
    JSONArray object = new JSONArray();
    for (DepartProjectData data : projectData) {
      DetachedCriteria criteria = DetachedCriteria.forClass(BasicData.class);
      criteria.add(Restrictions.eq("com", data.getCom()));
      criteria.add(Restrictions.eq("no", data.getEquipment().getE_number()));
      criteria.add(Restrictions.eq("datatype", data.getDataType().getD_key()));
      criteria.addOrder(Order.desc("Acquisitiontime"));
      //List<Date> listdate = new ArrayList<>();
      //List<String> listdata = new ArrayList<>();
      List<BasicData> datas = basicDataService.findByConditions(criteria);
      if (datas.size()>0){
          //datas.get(0);
        object.add(datas.get(0));
      }
    }

    return object;
  }


  /**
   * @throws
   * @title TODO
   * @description 首页数据图表查询
   * @author 阿良
   * @param: request
   * @param: data
   * @param: meun
   * @updateTime 2020/3/11 10:31
   * @return: com.wcgksoft.common.util.Layui
   */
  @ResponseBody
  @RequestMapping(value = "findHomecontainer")
  public JSONObject findHomecontainer(HttpServletRequest request) throws Exception {
    Session session = SecurityUtils.getSubject().getSession();//得到工具类
//    EnterpriseProject enterpriseProject = (EnterpriseProject) session.getAttribute("project");//获取选中的片区/区域
//    Integer id2 = enterpriseProject.getId();
    SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");//获得企业用户
    //sysusercon.add(Restrictions.eq("enterprise.id", sysUser.getEnterprise().getId()));
//    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DepartProjectData.class);
//    detachedCriteria.add(Restrictions.eq("bbbbid", id2));
    //detachedCriteria.add(Restrictions.eq("",""));
    /*------*/
    DetachedCriteria detachedCriteriaep = DetachedCriteria.forClass(EnterpriseProject.class);
    detachedCriteriaep.add(Restrictions.eq("enterprise.id",sysUser.getEnterprise().getId()));
    List<EnterpriseProject> enterpriseProjects = enterpriseProjectService.findByConditions(detachedCriteriaep);


    HashMap<String, HashMap> type = new HashMap<>();
    JSONObject object2 = new JSONObject(new LinkedHashMap());

    HashMap<Object, Object> wd = new HashMap<>();
    HashMap<Object, Object> sd = new HashMap<>();
    HashMap<Object, Object> co2 = new HashMap<>();
    HashMap<Object, Object> aq = new HashMap<>();
    HashMap<Object, Object> gzqd = new HashMap<>();
    HashMap<Object, Object> fs = new HashMap<>();
    for (EnterpriseProject project : enterpriseProjects) {

      DetachedCriteria detachedCriterias = DetachedCriteria.forClass(DepartProjectData.class);
      detachedCriterias.add(Restrictions.eq("bbbbid", project.getId()));
      List<DepartProjectData> projectData = departProjectDataService.findByConditions(detachedCriterias);
      for (DepartProjectData data : projectData) {

        DetachedCriteria criteria = DetachedCriteria.forClass(BasicData.class);
        criteria.add(Restrictions.eq("com", data.getCom()));
        criteria.add(Restrictions.eq("no", data.getEquipment().getE_number()));
        criteria.add(Restrictions.eq("datatype", data.getDataType().getD_key()));
        criteria.add(Restrictions.sqlRestriction(" acquisition_time >=  NOW() - interval 24 hour  order by acquisition_time asc;"));
        List<BasicData> datas = basicDataService.findByConditions(criteria);
        if (datas.size()>0){
          HashMap<Object, Object> map = new HashMap<>();
          map.put("datas",datas);
          map.put("pro",data);
          if (data.getDataType().getD_key().equals("wd")){
            wd.put(project.getProjectName(),map);
          }else if(data.getDataType().getD_key().equals("sd")){
            sd.put(project.getProjectName(),map);
          }else if(data.getDataType().getD_key().equals("co2")){
            co2.put(project.getProjectName(),map);
          }else if(data.getDataType().getD_key().equals("aq")){
            aq.put(project.getProjectName(),map);
          }else if(data.getDataType().getD_key().equals("gzqd")){
            gzqd.put(project.getProjectName(),map);
          }else if(data.getDataType().getD_key().equals("fs")){
            fs.put(project.getProjectName(),map);
          }

        }
      }

    }

    object2.put("wd",wd);
    object2.put("sd",sd);
    object2.put("gzqd",gzqd);
    object2.put("co2",co2);
    object2.put("aq",aq);
    object2.put("fs",fs);
    /*------*/
  /*  List<DepartProjectData> projectData = departProjectDataService.findByConditions(detachedCriteria);
    JSONArray object = new JSONArray();
    for (DepartProjectData data : projectData) {
      JSONObject object1 = new JSONObject();
      DetachedCriteria criteria = DetachedCriteria.forClass(BasicData.class);
      criteria.add(Restrictions.eq("com", data.getCom()));
      criteria.add(Restrictions.eq("no", data.getEquipment().getE_number()));
      criteria.add(Restrictions.eq("datatype", data.getDataType().getD_key()));
      criteria.add(Restrictions.sqlRestriction(" DATE_SUB(CURDATE(), INTERVAL 2 DAY) <= date(acquisition_time) order by acquisition_time asc;"));
      //List<Date> listdate = new ArrayList<>();
      //List<String> listdata = new ArrayList<>();
      List<BasicData> datas = basicDataService.findByConditions(criteria);
        //datas.get(0);
      if(datas.size()>0){
        object1.put(datas.get(0).getDatatype(),datas);
        object.add(object1);
      }



    }*/

    return object2;
  }

}
